package com.woniuxy.ticketmovie.exception;/*
@author houguai
@create 2021-02-24 15:49
*/


import com.woniuxy.ticketmovie.entity.ResponceResult;
import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class TicketExceptionHandler {

    @ExceptionHandler(TypeNameExsitException.class)
    public ResponceResult<Void> exceptionHandle(){

        return new ResponceResult<>(501,"名称已存在");
    }

    @ExceptionHandler(DataAccessException.class)
    public ResponceResult<Void> daExceptionHandle() {

        return new ResponceResult<>(500,"参数异常");
    }

    /**
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponceResult<Object> bindException(MethodArgumentNotValidException e) {

//        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
        Map<String,String> msg=new HashMap<>();

        e.getBindingResult().getFieldErrors().forEach(b->msg.put(b.getField(),b.getDefaultMessage()));

        ResponceResult responceResult=new ResponceResult();

        responceResult.setCode(105);
        responceResult.setMsg("参数异常");
        responceResult.setData(msg);

        return responceResult;
    }


}
